package com.upbos.sso.resolver;

import com.upbos.sso.SsoManager;
import com.upbos.sso.UserContext;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserContextArgumentResolver implements HandlerMethodArgumentResolver {

    private SsoManager ssoManager;

    public UserContextArgumentResolver() {
        super();
    }

    public UserContextArgumentResolver(SsoManager ssoManager) {
        this.ssoManager = ssoManager;
    }

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType() != null
                && methodParameter.getParameterType().equals(UserContext.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        UserContext context = new UserContext(ssoManager, request);
        return context;
    }
}
